package
{
	import extend.php.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.text.*;
	
	import mortal.common.global.*;
	import mortal.common.preLoadPage.*;
	
	[SWF(width="1", height="1", frameRate="24", backgroundColor ='0x000000')]
	public class Preloader extends Sprite
	{
		private var _text:TextField;
		
		public function Preloader()
		{
			
			if (stage)
			{
				this.init();
			}
			else
			{
				this.addEventListener(Event.ADDED_TO_STAGE, this.init);
			}
		}
		
		private function init(event:Event = null) : void
		{
			GameLoadBar.instance.gameRoot = stage;
			ParamsConst.instance.init(stage);
			if (PHPSender.isCreateRole)
			{
				PHPSender.sendToURLByPHP(SenderType.Preloader);
			}
			PreLoginProxy.instance.rootStage = stage;
			PreLoginProxy.instance.login();
			this.addEventListener(Event.ENTER_FRAME, this.onEnterFrameHandler);
		}
		
		private function onEnterFrameHandler(event:Event) : void
		{
			if (loaderInfo.bytesLoaded == loaderInfo.bytesTotal)
			{
				removeEventListener(Event.ENTER_FRAME, this.onEnterFrameHandler); 
				this._text = new TextField();
				this._text.selectable = false;
				this._text.text = "正在进入游戏...";
				this._text.textColor = 16777215;
				this._text.x = stage.stageWidth / 2 - 30;
				this._text.y = stage.stageHeight / 2 - 15;
				this._text.autoSize = TextFieldAutoSize.LEFT;
				this.addChild(this._text);
				GameLoadBar.resourceLoader = new Loader();
				GameLoadBar.resourceLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.loadCompleteHandler);
				GameLoadBar.resourceLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, this.loadProgressHandler);
				GameLoadBar.resourceLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.loadErrorHandler);
				GameLoadBar.resourceLoader.load(new URLRequest(PathConst.mainPath + "assets/modules/PreloaderPage/preLoadPage.swf" + "?v=" + ParamsConst.instance.flashVersion));
			}
		}
		
		private function loadCompleteHandler(event:Event) : void
		{
			GameLoadBar.resourceLoader.removeEventListener(Event.COMPLETE, this.loadCompleteHandler);
			this.removeChild(this._text);
			this._text = null;
			GameLoadBar.instance.show();
			GameLoadBar.instance.setProgress(PreloaderConfig.LOGIN_GAME, 0.8, 1);
		}
		
		private function loadProgressHandler(event:ProgressEvent) : void
		{
			this._text.text = "正在进入游戏...  " + Math.round(100 * event.bytesLoaded / event.bytesTotal) + "%";
		}
		
		private function loadErrorHandler(event:ErrorEvent) : void
		{
			trace("资源加载失败！" + (event.target as LoaderInfo).url);
		}
	}
}